<!DOCTYPE HTML>
<html>
<head>
  <title>Heater Control</title>
<meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" />
<link rel="stylesheet" href="css/themes/custom-theme.css" />
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script src="js/moment.min.js"></script>

<script type="text/javascript">

function wifi_check_valid(encrypt, passwd) {
  if (encrypt == 'wep') {
    if (passwd.length == 10) {
      var m = /[0-9a-fA-F]{10}/;
      if (!m.test(passwd))
        return false;
    } else if (passwd.length == 26) {
      var m = /[0-9a-fA-F]{26}/;
      if (!m.test(passwd))
        return false;
    } else if (passwd.length != 5 && passwd.length != 13)
      return false;

  } else if (encrypt.substr(0,3) == 'wpa') {
    if (passwd.length == 64) {
      var m = /[0-9a-fA-F]{64}/;
      if (!m.test(passwd))
        return false;
    } else if (passwd.length<8 || passwd.length > 63)
      return false;
  }
  return true;
}

var wifi_connected;
var wifi_selected;
var wifi_passwd;
var wifi_encrypt;

function wifi_submit() {
  if (wifi_encrypt === "none")
    wifi_passwd = "";
  $.post("net.tt", {command: "connect", ssid: wifi_selected, passwd: wifi_passwd});
}

function wifi_warning() {
  wifi_passwd = $('#wifi_pw')[0].value;
  $('#wifi_warn_title').html('Are you sure you want to connect to "' + wifi_selected + '" ?');
  setTimeout( function(){ $("#wifi_warn_pop").popup("open"); }, 100 );
}

function wifi_select(ssid, encrypt) {
  wifi_selected = ssid;
  wifi_encrypt = encrypt;
  $('#wifi_pw')[0].value = '';
  if (encrypt === "none")
    wifi_warning();
  else
    $("#wifi_pw_pop").popup("open");
}

$(document).ready(function () {

  $.post("net.tt", {command: "get_connected"}, // init
    function(textVal){
      wifi_connected = textVal.replace(/(\r\n|\n|\r)/gm,"");
  });

  $('#wifi_collapsible').bind('expand', function(){
    $('<ul>').attr({'id':'wifi_listview','data-role':'listview'}).appendTo('#wifi_collapsible [data-role="content"]');
    $.post('net.tt', {command: "scan"}, function(json) {
      $.each(json,function(i){
        var level = (Number(json[i].level) / 20) >> 0;
        if (level == 5) level = 4;
        level = '<img src="img/' + level + '.png" class="ui-li-icon">';

        var locked = '';
        if (json[i].encrypt != "none") locked = '<img src="img/locked.png" class="ui-li-icon">';

        var online = '';
        if (json[i].ssid === wifi_connected) online = '<img src="img/online.png" style="float:right; max-height:20px">';

        $('<li>').append('<a href="#" onclick="wifi_select(\'' + json[i].ssid + '\', \'' + json[i].encrypt + '\')">'
                         + locked + level + json[i].ssid + online + '</a>').appendTo('#wifi_listview');
        $('#wifi_listview').listview().listview('refresh');
      });
    }, 'json');
  });

  $('#wifi_collapsible').bind('collapse', function() {
    $('#wifi_collapsible_content').html('');
  });

  $('#wifi_show_pw').on('change', function() {
    if (this.checked) {
      $('#wifi_pw')[0].type = 'text';
      $('#wifi_pw_done').removeClass('ui-disabled');
    } else $('#wifi_pw')[0].type = 'password';
  });

  $(document).delegate('#wifi_pw', 'keyup', function() {
    if (wifi_check_valid(wifi_encrypt, $('#wifi_pw')[0].value) == false)
      $('#wifi_pw_done').addClass('ui-disabled');
    else
      $('#wifi_pw_done').removeClass('ui-disabled');
  });

  (function check_online() {
    $.ajax({
      type: 'GET',
      url: 'check_online_dev',
      success: function(textVal) {
        $('#header-string').html('Heater Control ' + '(' + textVal + ')');
      },
      complete: function() {
        setTimeout(check_online, 20000);
      }
    });
  })();

});

</script>

</head>

<body>

<div data-role="header" data-position="fixed">
    <span class="ui-title" id="header-string">Heater Control</span>
</div>


<div data-role="collapsible-set" data-theme="c" data-content-theme="d">

<div id="wifi_collapsible" data-role="collapsible" data-collapsed="true">
  <h3>Network</h3>
  <div id="wifi_collapsible_content" data-role="content">
  </div>
</div>

<div id="dev_name_collapsible" data-role="collapsible">
  <h3>Device Name</h3>
  <script type="text/javascript">
$('#dev_name_collapsible').bind('expand', function(){
  $.post('sys.tt', {command: 'get_hostname'},
    function(textVal){
      $('#dev_name')[0].value = textVal.replace(/(\r\n|\n|\r)/gm,"");
  });
});
function dev_name_submit() {
  $.post('sys.tt', {command: 'set_hostname', value: $('#dev_name')[0].value});
  $('#common_pop_p').html('Successed.');
  $('#common_pop').popup('open');
}
  </script>
  <form>
    Change the device name:
    <input type="text" id="dev_name" required pattern="[a-z0-9-]{1,20}" title="only a-z, 0-9 and '-' are allowed">
    <a href="#" onclick="dev_name_submit()" data-role="button" data-inline="true">Submit</a>
  </form>
</div>

<div data-role="collapsible">
  <h3>Away Setting</h3>
  <p>under development</p>
</div>

<div id="date_collapsible" data-role="collapsible">
  <h3>Date &amp; Time</h3>
  <script type="text/javascript">
$('#date_collapsible').bind('expand', function(){
  $.post('sys.tt', {command: 'get_date'},
    function(textVal){
      var datetime = textVal.replace(/(\r\n|\n|\r)/gm,"").split(" ");
      $('#date_d')[0].value = datetime[0];
      $('#date_t')[0].value = datetime[1];
  });
});
function date_submit() {
  var datetime = $('#date_d')[0].value + " " + $('#date_t')[0].value;
  $.post('sys.tt', {command: 'set_date', value: datetime});
  $('#common_pop_p').html('Successed.');
  $('#common_pop').popup('open');
}
  </script>
  <form>
    <label for="date_d">Date:</label>
    <input type="date" data-clear-btn="true" id="date_d" value="">
    <label for="date_t">Time:</label>
    <input type="time" data-clear-btn="true" id="date_t" value="">
    <a href="#" onclick="date_submit()" data-role="button" data-inline="true">Modify</a>
  </form>
</div>

<div id="timer_collapsible" data-role="collapsible">
  <h3>Timer</h3>
  <script type="text/javascript">
var timer_json; // cron: M H d m w, action: on
var timer_select_cron;
var timer_select_action;

function timer_post() {
  //var post_string = '';
  //$.each(timer_json,function(i){
  //  post_string += timer_json[i].cron + ' /duke/power_' + timer_json[i].action + '\n';
  //});
  $.post('sys.tt', {command: 'set_timer', value: JSON.stringify(timer_json)});
  $('#common_pop_p').html('Successed.');
  setTimeout( function(){ $('#common_pop').popup('open'); }, 100 );
}

function timer_sync() {
  $('#timer_collapsible_content').html(""); // clean
  $('<ul>').attr({'id':'timer_listview','data-role':'listview'}).appendTo('#timer_collapsible [data-role="content"]');
  $.each(timer_json,function(i){
    var icon = '<img src="img/' + timer_json[i].action + '.png" class="ui-li-icon">';
    var cron_array = timer_json[i].cron.split(" ");
    var time_str;

    if (cron_array[2] != "*") { // day
      // "10-01 13:03"
      var tmp_str = cron_array[3] + "-" + cron_array[2] + " " + cron_array[1] + ":" + cron_array[0];
      time_str = moment(tmp_str, "MM-DD H:m").format("MMMM Do, h:m A");
    } else if (cron_array[4] != "*") { // week
      switch (cron_array[4]) {
        case "1-5":
          time_str = "Monday to Friday";
          break;
        case "6,7":
          time_str = "Saturday and Sunday";
          break;
        case "0-4":
          time_str = "Sunday to Thursday";
          break;
        case "5,6":
          time_str = "Friday and Saturday";
          break;
      }
      time_str += ", " + moment(cron_array[1] + ":" + cron_array[0], "H:m").format("h:m A");
    } else
      time_str = "Every Day, " + moment(cron_array[1] + ":" + cron_array[0], "H:m").format("h:m A");

    //time_str = "Power " + timer_json[i].action + " @ " + time_str;

    $('<li>').attr({'data-icon':'delete'}).append(
      '<a href="#" onclick="timer_select(\'' + timer_json[i].cron + '\', \'' + timer_json[i].action + '\')">'
                     + icon + time_str + '</a>').appendTo('#timer_listview');
    $('#timer_listview').listview().listview('refresh');
  });
}

function timer_select(cron, action) {
  timer_select_cron = cron;
  timer_select_action = action;
  $("#timer_warn_pop").popup("open");
}

function timer_rm() {
  var index;
  $.each(timer_json,function(i){
    if ((timer_json[i].cron == timer_select_cron) && (timer_json[i].action == timer_select_action))
      index = i;
  });
  timer_json.splice(index, 1);
  timer_sync();
  timer_post();
}

$('#timer_collapsible').bind('expand', function(){
  $.post('sys.tt', {command: 'get_timer'},
    function(textVal){
      timer_json = textVal;
      timer_sync();
  }, 'json');
  $.post('sys.tt', {command: 'get_date'},
    function(textVal){
      var datetime = textVal.replace(/(\r\n|\n|\r)/gm,"").split(" ");
      $('#timer_d')[0].value = datetime[0];
      $('#timer_t')[0].value = datetime[1];
  });
});

function timer_add() {
  var time_array = $('#timer_t').val().split(":");
  var date_array = $('#timer_d').val().split("-");
  var crontab = time_array[1] + " " + time_array[0] + " ";

  switch ($('#timer_type').val()) {
  case 'all':
    crontab += "* * *";
    break;
  case 'one':
    crontab += date_array[2] + " " + date_array[1] + " *";
    break;
  default:
    crontab += "* * " + $('#timer_type').val();
    break;
  }

  timer_json.push({cron: crontab, action: $('#timer_action').val()});
  timer_sync();
  timer_post();
}

$(document).ready(function () {
  $('#timer_type').bind("change", function() {
    if ($('#timer_type').val() == "one") {
      $('#timer_d').show();
      $('#timer_d_l').show();
    } else {
      $('#timer_d').hide();
      $('#timer_d_l').hide();
    }
  });
});
  </script>
  <div id="timer_collapsible_content" data-role="content">
  </div>
  <h3>New:</h3>
  <form>
    <label for="timer_type">Select type:</label>
    <select id="timer_type">
      <option value="all">Every day</option>
      <option value="1-5">Every Monday to Friday</option>
      <option value="6,7">Every Saturday and Sunday</option>
      <option value="0-4">Every Sunday to Thursday</option>
      <option value="5,6">Every Friday and Saturday</option>
      <option value="one">Specify a day</option>
    </select>
    <label for="timer_d" id="timer_d_l" style="display:none">Date:</label>
    <input type="date" data-clear-btn="true" id="timer_d" value="" style="display:none">
    <label for="timer_t">Time:</label>
    <input type="time" data-clear-btn="true" id="timer_t" value="">
    <label for="timer_action">Action:</label>
    <select id="timer_action">
      <option value="on">Power on</option>
      <option value="off">Power off</option>
    </select>
    <a href="#" onclick="timer_add()" data-role="button" data-inline="true">Add</a>
  </form>
</div>

<div id="calibrate_collapsible" data-role="collapsible">
  <h3>Thermostat Calibration</h3>
  <script type="text/javascript">
var calibrate_current;

$('#calibrate_collapsible').bind('expand', function(){
  $.post('mcu.tt', {command: 'read_temperature'},
    function(textVal){
      calibrate_current = Math.round(Number(textVal)*10)/10;
      $("#calibrate_b_c").html(calibrate_current  + " °C");
      $("#calibrate_b_f").html((Math.round(((9/5)*calibrate_current+32)*10)/10) + " °F");
      calibrate_sync();
  });
});

function calibrate_sync() {
  delta = Number($('#calibrate').val());
  calibrate_after = Math.round((calibrate_current+delta)*10)/10;
  $("#calibrate_a_c").html(calibrate_after + " °C");
  $("#calibrate_a_f").html((Math.round(((9/5)*calibrate_after+32)*10)/10) + " °F");
}

$(document).ready(function () {
  $('#calibrate').bind("change", function() {
    calibrate_sync();
  });
});

function calibrate_submit() {
  //$.post('sys.tt', {command: 'set_date', value: datetime});
  $('#common_pop_p').html('Successed.');
  $('#common_pop').popup('open');
}
  </script>
  <form>
    <table border="0" width="260px">
      <tr>
        <td>Befor calibration:</td>
        <td id="calibrate_b_c">--.- 'C</td>
        <td id="calibrate_b_f">--.- 'F</td>
      </tr>
      <tr>
        <td>After calibration:</td>
        <td id="calibrate_a_c">--.- 'C</td>
        <td id="calibrate_a_f">--.- 'F</td>
      </tr>
    </table>
    <input type="range" id="calibrate" min="-5" max="5" value="0" step="0.1">
	<a href="#" onclick="$('#calibrate').val(0).slider('refresh');" data-role="button" data-inline="true" >Reset</a>
	<a href="#" onclick="calibrate_submit()" data-role="button" data-inline="true">Set</a>
  </form>

</div>

<div id="manual_collapsible" data-role="collapsible">
  <h3>Manual Control</h3>
  <script type="text/javascript">
$(document).ready(function () {
  $('#manual_reboot').bind("change", function() {
    $('#manual_reboot').slider("disable");
    $.post('sys.tt', {command: 'reboot'});
    $('#common_pop_p').html('Rebooting, please wait ...');
    $('#common_pop').popup('open');
  });
  $('#manual_power').bind("change", function() {
    $.post('sys.tt', {command: 'set_power', value: $('#manual_power').val()});
    $('#common_pop_p').html('Successed.');
    $('#common_pop').popup('open');
  });
});
$('#manual_collapsible').bind('expand', function(){
  $.post('sys.tt', {command: 'get_power'},
    function(textVal){
      $('#manual_power').val(textVal.replace(/(\r\n|\n|\r)/gm,"")).slider('refresh');
  });
});
  </script>
  <form>
    <div data-role="fieldcontain">
      <label for="manual_reboot">Slide to reboot:</label>
      <select id="manual_reboot" data-role="slider">
        <option value="off">—»</option>
        <option value="on">Done</option>
      </select>
    </div>
    <div data-role="fieldcontain">
      <label for="manual_power">Device Power:</label>
      <select id="manual_power" data-role="slider">
        <option value="off">Off</option>
        <option value="on">On</option>
      </select>
    </div>
  </form>
</div>

</div> <!-- end of collapsible set -->

<div data-role="footer" data-id="foo1" data-position="fixed">
	<div data-role="navbar">
		<ul>
			<li><a href="temperature.html" rel="external">Temperature</a></li>
			<li><a href="humidity.html" rel="external">Humidity</a></li>
			<li><a href="setting.html" class="ui-btn-active ui-state-persist">Setting</a></li>
		</ul>
	</div><!-- /navbar -->
</div><!-- /footer -->

<div data-role="popup" id="wifi_pw_pop" class="ui-corner-all">
  <form>
	<div style="padding:10px 20px;">
	  <label for="wifi_pw" class="ui-hidden-accessible">Password:</label>
	  <input type="password" id="wifi_pw" value="" placeholder="password" />

      <input type="checkbox" id="wifi_show_pw" class="custom" data-mini="true">
      <label for="wifi_show_pw">show passwd</label>

	  <a href="#" data-rel="back" data-role="button" data-inline="true">Cancel</a>
      <a href="#" onclick="wifi_warning()" id="wifi_pw_done" class="ui-disabled" data-rel="back" data-role="button" data-inline="true">Done</a>
	</div>
  </form>
</div>

<div data-role="popup" id="wifi_warn_pop" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all">
  <div data-role="header" data-theme="a" class="ui-corner-top">
	<h1>Warning</h1>
  </div>
  <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
	<h3 class="ui-title" id="wifi_warn_title"></h3>
	<p>This makes you disconnect to the device.</p>
	<a href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c">Cancel</a>
	<a href="#" onclick="wifi_submit()" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-theme="b">Connect</a>
  </div>
</div>

<div data-role="popup" id="timer_warn_pop" data-overlay-theme="a" data-theme="c" style="max-width:400px;" class="ui-corner-all">
  <div data-role="header" data-theme="a" class="ui-corner-top">
	<h1>Warning</h1>
  </div>
  <div data-role="content" data-theme="d" class="ui-corner-bottom ui-content">
	<h3 class="ui-title">Are you want to delete this item?</h3>
	<a href="#" data-role="button" data-inline="true" data-rel="back" data-theme="c">Cancel</a>
	<a href="#" onclick="timer_rm()" data-role="button" data-inline="true" data-rel="back" data-transition="flow" data-theme="b">Yes</a>
  </div>
</div>

<div data-role="popup" id="common_pop">
    <p id="common_pop_p"></p>
</div>

</body>
</html>
